package com.heima.app.gateway.filter;

import com.heima.app.gateway.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/** 全局过滤器
 * @author dongcy
 * @date 2024/11/6 15:33
 * @description AuthorizeFilter
 */
@Component
@Slf4j
public class AuthorizeFilter implements Ordered, GlobalFilter {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取request+response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //判断是否登录
        if (request.getURI().getPath().contains("/login")){
            //访问登录接口--放行
            return chain.filter(exchange);
        }

        //获取toekn
        String token = request.getHeaders().getFirst("token");

        //判断toekn
        if (StringUtils.isEmpty(token)){
            //toekn未空   报错401
            response.setRawStatusCode(HttpStatus.UNAUTHORIZED.value());
            return response.setComplete();
        }

        //校验token是否有效
        try {
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int num = AppJwtUtil.verifyToken(claims);
            if (num == 1 || num == 2){
                //token失效
                response.setRawStatusCode(HttpStatus.UNAUTHORIZED.value());
                return response.setComplete();
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setRawStatusCode(HttpStatus.UNAUTHORIZED.value());
            return response.setComplete();
        }

        //放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
